<?php

namespace catchAdmin\customs\controller;

use catcher\base\CatchRequest as Request;
use catcher\CatchResponse;
use catcher\base\CatchController;
use catchAdmin\customs\model\Account as AccountModel;
use catcher\library\excel\reader\Reader;
use think\Response;
use think\response\Json;
use think\facade\Db;

class Account extends CatchController
{
    
    protected $accountModel;
    
    /**
     *
     * @time 2021/12/27 16:17
     * @param AccountModel $accountModel
     * @return mixed
     */
    public function __construct(AccountModel $accountModel)
    {
        $this->accountModel = $accountModel;
    }
    
    /**
     * 账册列表
     * @time 2021/12/27 16:17
     * @param CatchRequest $request
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function index(): \think\response\Json   
    {
        return CatchResponse::paginate($this->accountModel->getList());
    }
    
    /**
     *  编辑账册
     * @time 2021/12/27 16:17
     * @param Request $request
     * @return Response
     */
    public function update(Request $request) : Response
    {
        $type = $request->post('type');
        if (!$type) {
            return CatchResponse::fail('缺少参数');
        }
        if ($type === 1) {
            $id = $request->post('id');
            if (!$id) {
                return CatchResponse::fail('缺少参数');
            }
             //订单表
            $Info = AccountModel::where(array('id' => $id))->find()->toArray();
            if (!$Info) {
                return CatchResponse::fail('没有该数据');
            }
            return CatchResponse::success($Info, '查询成功');
        }  elseif ($type === 2) {
            $form = $request->post('form');
            if (!$form) {
                return CatchResponse::fail('缺少参数');
            }
            $info = json_decode(json_encode($form), true);
            $data = Db::name('db_customs_record_material')->save($info);
            if ($data) {
                return CatchResponse::success([], '编辑成功');
            } else {
                return CatchResponse::fail('编辑失败');
            }
        }
    }
    
    /**
     * 删除账册
     * @time 2021/12/27 16:17
     * @param $id
     * @return Response
     */
    public function delete($id) : Response
    {
        return CatchResponse::success($this->accountModel->deleteBy($id));
    }
    /**
     *
     * @time 2021/12/27 16:17
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function importAccount(Request $request)
    {
        // 获取表单上传文件
        $files = request()->file();
        try {
            //10M以下csv,xlsx,xls文件
            validate(['file' => 'fileSize:10485760|fileExt:csv,xlsx,xls'])->check($files);
            $fields = [
                ['field' => 'record_material_no', 'label' => '账册备案料号','empty' => 'NO'],
                ['field' => 'barcode', 'label' => '条形码', 'empty' => 'NO'],
                ['field' => 'g_code', 'label' => '海关编码', 'empty' => 'NO'],
                ['field' => 'g_name', 'label' => '海关备案商品名称', 'empty' => 'NO'],
                ['field' => 'g_model', 'label' => '商品规格', 'empty' => 'NO'],
                ['field' => 'origin_country_code', 'label' => '原产国(地区）编码', 'empty' => 'NO'],
                ['field' => 'trade_country_code', 'label' => '贸易国', 'empty' => 'NO'],
                ['field' => 'currency_code', 'label' => '币制', 'empty' => 'NO'],
                ['field' => 'unit', 'label' => '计量单位', 'empty' => 'NO'],
                ['field' => 'unit1', 'label' => '法定计量单位', 'empty' => 'NO'],
                ['field' => 'unit2', 'label' => '法定第二计量单位', 'empty' => 'YES'],
                ['field' => 'qty1', 'label' => '法定单位数量', 'empty' => 'NO'],
                ['field' => 'qty2', 'label' => '法定第二单位数量', 'empty' => 'YES'],
                ['field' => 'net_weight', 'label' => '净重(公斤）', 'empty' => 'NO'],
                ['field' => 'gross_weight', 'label' => '毛重(公斤）', 'empty' => 'NO']
            ];
            $msg = [];
            $requests = $request;
            $this->importExcl(array_column($fields, 'field'), $files['file'], function ($data) use ($fields, &$msg,&$requests) {

                if (count($data) > 1) {
                    // 启动事务
                    Db::startTrans();
                    $success = 0;
                    foreach ($data as $key => $value) {
                        if ($key === 0) {
                            foreach ($fields as $k => $v) {
                                //验证表格头部是否模板字段
                                if (strpos($value[$v['field']], $v['label']) === false) {
                                    $msg = ['code' => 10001, 'message' => '模板表头' . $value[$v['field']] . '不匹配，请下载最新模板'];
                                    Db::rollback();
                                    return;

                                }
                            }
                        } else {
                            $params = [];
                            //查询是否存在数据
                            $record_material_no = Db::table('db_customs_record_material')->where([
                                                                    'record_material_no'=>$value['record_material_no']
                                                                    ])->value('record_material_no');
                            foreach ($fields as $k => $v) {
                                if(empty($record_material_no)) {
                                    if($v['empty'] === 'NO'){
                                        if(empty($value[$v['field']])) {
                                            $msg = ['code' => 10001, 'message' =>'新增数据,第' . ($key + 1) . '行' . $v['label'] . '不能为空'];
                                            Db::rollback();
                                            return;
                                        }
                                    }
                                }
                                if($v['field'] === 'currency_code'){
                                    // 币制
                                   $value[$v['field']] = $this->encoded($value[$v['field']],1);
                                }
                                
                                if($v['field'] === 'trade_country_code' || $v['field'] === 'origin_country_code' ){
                                    // 贸易国/原产国
                                   $value[$v['field']] = $this->encoded($value[$v['field']],2);
                                }

                                if($v['field'] === 'unit' || $v['field'] === 'unit1' || $v['field'] === 'unit2'){
                                    //计量单位/法定计量单位/法定第二计量单位
                                   $value[$v['field']] = $this->encoded($value[$v['field']],3);
                                }
                                $params[$v['field']] = $value[$v['field']];
                            }
                            $params['creator_id'] = $requests->user()->id;
                            $params['created_at'] = time();
                            $params['updated_at'] = time();
                            
                             if(!empty($record_material_no)){
                                 //修改
                                 unset($params['created_at']);
                                 $params = array_filter($params);
                                 $res = Db::table('db_customs_record_material')->where(['record_material_no'=>$record_material_no])->save($params);
                             }else{
                                 //添加
                                 $res = Db::table('db_customs_record_material')->save($params);
                             }
                            if (!$res) {
                                $msg = ['code' => 10002, 'message' => '第' . ($key + 1) . '行导入失败，请检查'];
                                Db::rollback();
                                return;
                            } else {
                                $success++;
                            }
                        }
                    }
                    if ($success > 0) {
                        Db::commit();
                    } else {
                        Db::rollback();
                    }
                    $msg = ['code' => 10000, 'message' => '操作成功，成功导入' . $success . '条数据'];
                } else {
                    $msg = ['code' => 10002, 'message' => '没有需要导入的数据'];
                }
            });
            if ($msg['code'] === 10000) {
                return CatchResponse::success([], $msg['message']);
            } else {
                return CatchResponse::fail($msg['message']);
            }
        } catch (\think\exception\ValidateException $e) {
            return CatchResponse::fail($e->getMessage());
        }
    }

    /**
     * 导入
     * @param Reader $reader
     * @param $fields
     * @param $file
     * @return bool
     */
    public function importExcl($fields, $file, callable $callable)
    {
        $excel = new class($fields) extends Reader {
            protected $fields;

            public function __construct($fields)
            {
                $this->fields = $fields;
            }

            public function headers()
            {
                // TODO: Implement headers() method.
                return $this->fields;
            }
        };
        $excel->import($file)->then(function ($data) use ($callable) {
            $callable($data);
        });
    }
    /**
     * 从文件中找到编码
     * @time 2021/12/27 16:17
     * @return Response
     */
    public function encoded($str,$type)
    {
        $label = str_replace(" ",'',$str);
        if($type === 1){
            //币制
            $path = "json/currency.json";
        } else if($type === 2){
           //国家
            $path = "json/tradeCountry.json";
        } else if($type === 3){
           //单位
            $path = "json/unit.json";
        }
        $json_string = file_get_contents($path);

        $arr = json_decode($json_string,true);

        foreach ($arr as $k => $v) {
            if($v['label'] === $label || $v['value'] === $label){
                return $v['value'];
            }
        }
        return $label;
    }
}